using Microsoft.AspNetCore.Mvc;
using CRUD.Repository;
using CRUD.Models;
using System.Linq;
using CRUD.RequestParam;
using System.Collections.Generic;

namespace CRUD.Controllers
{
    public class CrudController : Controller
    {
        public IActionResult Index()
        {
            var a = new EfRepository<Product>();
            var b = a.Table.Where(x => x.IsDeleted == false).ToList();
            return View(b);

        }
            public IActionResult CreateOrEdit(int id)
            {
                var a = new EfRepository<Product>();
            var b = a.Table.Where(x => x.Id == id).FirstOrDefault();
            return View(b);
            }
            [HttpPost]
            public IActionResult Save(Request model)
            {
                var a = new EfRepository<Product>();
         
            if (model.Id > 0)
            {
                var b = a.GetById(model.Id);
                if (b != null)
                {
                    b.ProductName =model.ProductName;
                    b.Supplier =model.Supplier;
                    b.Price =model.Price;
                    b.Stock =model.Stock;
                    b.Remarks =model.Remarks;
                    a.Update(b);
                }
            }
            else
            {
                a.Insert(
                new Product
                {
                    ProductName = model.ProductName,
                    Supplier = model.Supplier,
                    Price = model.Price,
                    Stock = model.Stock,
                    Remarks = model.Remarks
                   
                });
            }




            return Ok();
            }
            public IActionResult Query(Query request)
            {
                var a = new EfRepository<Product>();
            List<Product> b;
           
            if (request != null && request.Keyword != null && request.Keyword.Length > 0)
            {
                b = a.Table
                            .Where(x => x.IsDeleted == false && (x.ProductName.Contains(request.Keyword) || x.Remarks.Contains(request.Keyword) || x.Supplier.Contains(request.Keyword) ))
                            .ToList();
            }
            else
            {
                b = a.Table
            .Where(x => x.IsDeleted == false)
            .ToList();
            }


            return Json(b);
            }
            public IActionResult Delete(int id)
            {
                var a = new EfRepository<Product>();
            a.Delete(id);
            return RedirectToAction("Index");
            }
        
    }
    
}